package netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 帅小伙
 * @date 2022/1/17
 * @description
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    // 使用hashMap管理channel
    public static Map<String,Channel> channels = new HashMap<String,Channel>();
    public static Map<User,Channel> channels2 = new HashMap<User,Channel>();

    // 定义一个channel组  管理所有的channel
    //GlobalEventExecutor.INSTANCE 全局的事件执行器 是个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /*
     * 表示连接建立
     * 将当前channel加入到 channelGroup
     * */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 将该客户推送给其他全部在线的客户端
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "加入聊天"+sdf.format(new java.util.Date())+"/n");
        channelGroup.add(channel);

        channels.put("id",channel);
    }

    /*
    *  将该离线客户推送给其他全部在线的客户端
    * */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        //channelGroup.remove(channel); 不需要 自动去掉
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "离开聊天\n");

    }

    /*
     * channel  处于活动的状态
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "上线了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "离线了");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        // 根据不同的情况  会送不同的消息
        channelGroup.forEach(ch->{
           if(ch != channel){// 转发消息
               ch.writeAndFlush("[客户]"+channel.remoteAddress() +"发送消息"+ msg+"\n");
           }else{
               ch.writeAndFlush("{自己}发送了消息:"+msg+"\n");
           }
        });
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
